import React, { useState, useEffect } from 'react';
import {
  Form,
  Input,
  Button,
  DatePicker,
  Upload,
  Alert,
  Cascader,
  Space,
  message,
  Modal,
} from 'antd';
import {
  MinusCircleOutlined,
  DeleteOutlined,
  LoadingOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import { regionSelection } from '../../../services/login';
import moment from 'moment';

// import ImgCrop from 'antd-img-crop';
import 'antd/dist/antd.less';
import './BasicActivityForm.less';

export default function BasicActivityForm(props) {
  // console.log(props.editList);
  // todo 表单提交
  const { form } = props;

  // *--------------------------------------------------------
  const onFinish = (fieldsValue) => {};

  const onFinishFailed = (errorInfo) => {};

  const { RangePicker } = DatePicker;
  // ? 这是外置表单验证 在里面要这样写 {...rangeConfig}
  // const rangeConfig = {
  //   rules: [
  //     {
  //       type: 'array',
  //       required: true,
  //       message: 'Please select time!',
  //     },
  //   ],
  // };

  // todo 这是自定义左边的图片上传的组件，通过自带的 onChange 方法将数据上传给表单, value对象 是当前传进去的值
  // const UploadImgLeft = ({ value = {}, onChange }) => {
  //   const [fileListLeft, setFileListLeft] = useState([]);
  //   const onFileListChange = ({ fileList: newFileList }) => {
  //     setFileListLeft(newFileList);
  //     onChange && onChange(newFileList);
  //   };
  //   const onPreview = async (file) => {
  //     let src = file.url;
  //     if (!src) {
  //       src = await new Promise((resolve) => {
  //         const reader = new FileReader();
  //         reader.readAsDataURL(file.originFileObj);
  //         reader.onload = () => resolve(reader.result);
  //       });
  //     }
  //     const image = new Image();
  //     image.src = src;
  //     const imgWindow = window.open(src);
  //     imgWindow.document.write(image.outerHTML);
  //   };
  //   return (
  //     <Upload
  //       name="multipartFile"
  //       action="/campus/campusweb/upload/pictureUpload"
  //       thumbUrl="/campus/campusweb/upload/pictureUpload"
  //       listType="picture-card"
  //       fileList={fileListLeft}
  //       onChange={onFileListChange}
  //       onPreview={onPreview}
  //     >
  //       {fileListLeft.length < 1 && (
  //         <div className="uploadImg">
  //           <div className="uploadImgAdd">+</div>
  //           <div className="uploadImgText">添加图片</div>
  //         </div>
  //       )}
  //     </Upload>
  //   );
  // };

  // *---------------------------------------------------
  // todo 地区选择数据
  // todo 定义原始数据
  const [areaList, setAreaList] = useState([]);
  // todo 在 useEffect 里面发请求
  useEffect(async () => {
    // console.log(props.editList);
    const data = await regionSelection({ addressLevel: 1 });
    const firstArea = data.data;
    if (data.code == 200) {
      firstArea.forEach((item) => {
        item['value'] = item.addressCode;
        item['label'] = item.addressName;
        item['isLeaf'] = false;
      });
      setAreaList(firstArea);
    }

    // * ----------------------------------------------------
    // todo 这是地区选择的回填
    if (props.editList.id) {
      const dataTwo = await regionSelection({
        addressLevel: 2,
        parentId: props.editList.provinceCode,
      });
      if (dataTwo.code == 200) {
        const newDataTwoList = dataTwo.data.map((item) => {
          return { label: item.addressName, value: item.addressCode };
        });
        areaList.forEach((item) => {
          if (item.addressCode == props.editList.provinceCode) {
            item.children = newDataTwoList;
          }
        });
        setAreaList([...areaList]);
      }
    }
  }, [props.editList.id]);

  // todo 切换城市的事件
  const onChange = async (value, selectedOptions) => {
    // console.log(value, selectedOptions);
  };
  // todo 懒加载的回调
  const loadData = async (selectedOptions) => {
    // console.log(selectedOptions);
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const data = await regionSelection({
      addressLevel: 2,
      parentId: targetOption.addressCode,
    });

    if (data.code == 200) {
      const newDataList = data.data.map((item) => {
        return { label: item.addressName, value: item.addressCode };
      });
      targetOption.loading = false;
      targetOption.children = newDataList;
      setAreaList([...areaList]);
    } else {
      message.error('获取地区失败，请重新获取');
    }
  };

  // todo 文本域
  const { TextArea } = Input;

  // *--------------------------------------------------
  const [fileListRight, setFileListRight] = useState([]);
  const [imageUrl, setImageUrl] = useState('');

  useEffect(() => {
    const editList = props.editList;
    // console.log(editList);

    if (props.editList.id) {
      // todo 左边图片渲染
      setImageUrl(editList.pictureUrl);
      // todo 右边图片渲染
      setFileListRight([
        {
          uid: editList.thumbnailPictureKey,
          name: 'image.png',
          status: 'done',
          url: editList.thumbnailPictureUrl,
        },
      ]);
      // todo 第一页表单回填
      form.setFieldsValue({
        // todo 活动名称
        activityName: editList.activityName,
        // todo 活动时间
        rangePicker: [
          moment(editList.startDate, 'YYYY-MM-DD HH:mm'),
          moment(editList.endDate, 'YYYY-MM-DD HH:mm'),
        ],
        // todo 活动主办方
        activitySponsorName: editList.activityOrganizers ? editList.activityOrganizers : '',
        // todo 活动图
        uploadImgLeft: {
          fileList: [
            {
              response: {
                data: {
                  imgKey: editList.pictureKey,
                  imgUrl: editList.pictureUrl,
                },
              },
            },
          ],
        },

        // todo 地区选择
        regionSelection: [editList.provinceCode, editList.cityCode],
        // regionSelection: [editList.provinceName, editList.cityName],
        // todo 活动地点
        activityAddress: editList.activitySite ? editList.activitySite : '',
        // todo 活动内容
        activitiesTextField: editList.activityContent,
        // todo 活动缩略图
        uploadImgRight: {
          fileList: [
            {
              response: {
                data: {
                  imgKey: editList.thumbnailPictureKey,
                  imgUrl: editList.thumbnailPictureUrl,
                },
              },
            },
          ],
        },

        // todo 日程名称
        users: editList.scheduleVOS.map((item) => {
          return {
            first: item.scheduleName,
            last: moment(item.scheduleDate, 'YYYY-MM-DD HH:mm'),
          };
        }),
      });
    }
  }, [props.editList.id]);

  // * ------------------------------------------------------
  // todo 左边的图片上传写在里面的方法
  function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  const [loading, setLoading] = useState(false);

  const [thumbImageUrl, setThumbImageUrl] = useState('');

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (imageUrl) => {
        setLoading(false);
        setImageUrl(imageUrl);
        // setImageKey(1)
      });
    }
  };

  // * --------------------------------------------------
  // todo 右边的图片上传写在里面的方法
  const onChangeRight = ({ fileList: newFileList }) => {
    setFileListRight(newFileList);
  };

  const onPreviewRight = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow.document.write(image.outerHTML);
  };

  // * --------------------------------------------------
  // todo 虚拟 DOM
  return (
    <div className="basicActivityFormAllFirst">
      <div className="basicActivityFormAll">
        <div className="basicActivityTitle">
          <p>请填写基本活动信息</p>
        </div>
        {/* 表单开始 */}
        <Form
          form={form}
          className="basicActivityForm"
          name="basic"
          layout="vertical"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 20,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          {/* 这是 左右 Flex 的盒子 */}
          <div className="basicActivityFormFlex">
            {/* 这是左边的表单 */}
            <div className="basicActivityFormLeft">
              {/* 这是活动名称 */}
              <Form.Item
                label="活动名称"
                name="activityName"
                rules={[
                  {
                    required: true,
                    message: '请输入活动名称 !',
                  },
                ]}
              >
                <Input placeholder="请输入活动名称" />
              </Form.Item>
              {/* 这是活动日期 */}
              <Form.Item
                name="rangePicker"
                label="活动时间"
                rules={[
                  {
                    type: 'array',
                    required: true,
                    message: '请输入活动时间 !',
                  },
                ]}
              >
                <RangePicker showTime format="YYYY-MM-DD HH:mm" />
              </Form.Item>
              {/* 这是活动主办方 */}
              <Form.Item label="活动主办方" name="activitySponsorName">
                <Input placeholder="请输入活动主办方" />
              </Form.Item>
              {/* 这是左边图片上传表单 */}
              <Form.Item
                className="uploadImgLeft"
                name="uploadImgLeft"
                valuePropName="checked"
                label="活动图"
                rules={[
                  {
                    required: true,
                    message: '请添加活动图片 !',
                  },
                ]}
              >
                {/* 这是自定义左边图片上传表单组件 */}
                <Upload
                  name="multipartFile"
                  action="/campus/campusweb/upload/pictureUpload"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  onChange={handleChange}
                >
                  {imageUrl ? (
                    <img src={imageUrl} alt="avatar" style={{ height: '90px' }} />
                  ) : (
                    <div>
                      {loading ? <LoadingOutlined /> : <PlusOutlined />}
                      <div style={{ marginTop: 8 }}>Upload</div>
                    </div>
                  )}
                </Upload>
                {/* <UploadImgLeft /> */}
              </Form.Item>
              <Alert message="推荐尺寸: 1035*261" type="warning" showIcon />
            </div>
            {/* 这是右边表单 */}
            <div className="basicActivityFormRight">
              {/* 这是地区选择 */}
              <Form.Item
                label="地区选择"
                name="regionSelection"
                rules={[
                  {
                    required: true,
                    message: '请选择地区 !',
                  },
                ]}
              >
                <Cascader
                  options={areaList}
                  loadData={loadData}
                  onChange={onChange}
                  changeOnSelect
                  placeholder="请选择地区"
                />
              </Form.Item>
              {/* 这是活动地址填写 */}
              <Form.Item label="活动地点" name="activityAddress">
                <Input placeholder="请输入活动地点" />
              </Form.Item>
              {/* 这是活动内容文本域 */}
              <Form.Item
                label="活动内容"
                name="activitiesTextField"
                rules={[
                  {
                    required: true,
                    message: '请填写活动内容 !',
                  },
                ]}
              >
                <TextArea rows={2} placeholder="请输入活动内容" />
              </Form.Item>
              {/* 这是右边的图片上传的组件 */}
              <Form.Item
                name="uploadImgRight"
                valuePropName="checked2"
                label="缩略图"
                rules={[
                  {
                    required: true,
                    message: '请添加缩略图片 !',
                  },
                ]}
              >
                {/* 这是自定义右边图片上传表单组件 */}
                <Upload
                  name="multipartFile"
                  action="/campus/campusweb/upload/pictureUpload"
                  thumbUrl="/campus/campusweb/upload/pictureUpload"
                  listType="picture-card"
                  fileList={fileListRight}
                  onChange={onChangeRight}
                  onPreview={onPreviewRight}
                >
                  {fileListRight.length < 1 && '+ Upload'}
                </Upload>
                {/* <UploadImgRight /> */}
              </Form.Item>
              <Alert message="推荐尺寸: 168*216" type="warning" showIcon />
            </div>
          </div>

          {/* 这是下面活动日程规划的大盒子 */}
          <div className="editEventSchedule">
            {/* 这是 左右 Flex 盒子下面的第二个标题 */}
            <div className="basicActivityTitleTwo">
              <div className="one">请编辑活动日程规划</div>{' '}
              <div className="two">（可添加多条）</div>
            </div>
            <div className="scheduleName">日程名称</div>
            {/* 这是下面的添加任意条表单 */}
            <Form.List name="users">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, fieldKey, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                      <Form.Item
                        {...restField}
                        name={[name, 'first']}
                        fieldKey={[fieldKey, 'first']}
                      >
                        <Input placeholder="请输入日程名称" />
                      </Form.Item>
                      <Form.Item {...restField} name={[name, 'last']} fieldKey={[fieldKey, 'last']}>
                        <DatePicker
                          placeholder="请选择日程时间"
                          showTime
                          format="YYYY-MM-DD HH:mm"
                        />
                      </Form.Item>
                      <DeleteOutlined className="garbageCan" onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button type="dashed" onClick={() => add()} block>
                      + 添加
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </div>
        </Form>
        {/* 表单结束 */}
      </div>
    </div>
  );
}
